package com.fjwt.gz.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fjwt.gz.core.cache.RedisUtil;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.db.entity.ActivityWhitelistEntity;
import com.fjwt.gz.db.entity.ActivityWhitelistEntity;
import com.fjwt.gz.service.mapper.ActivityWhitelistMapper;
import com.fjwt.gz.service.mapper.ActivityWhitelistMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动白名单，无法参与 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class ActivityWhitelistService extends ServiceImpl<ActivityWhitelistMapper, ActivityWhitelistEntity> {
    @Autowired
    private ActivityWhitelistMapper activityWhitelistMapper;
    /**获取白名单列表**/
    public Map<String, ActivityWhitelistEntity> getActivityWhiteMap(Long activityId, Long redisOutTime){
        String activityWhitelistKey = String.format("%s%s:%s", Constants.REDIS_ACTIVITY.FILENAME, activityId, Constants.REDIS_ACTIVITY.WHITELIST);
        log.info("活动限制白名单redisKey:{}", activityWhitelistKey);
        List<ActivityWhitelistEntity> activityWhitelist = RedisUtil.getObject(activityWhitelistKey, List.class);
        if (activityWhitelist == null || activityWhitelist.size() == 0) {
            LambdaQueryWrapper<ActivityWhitelistEntity> activityWhitelistrWrapper = new LambdaQueryWrapper<>();
            activityWhitelistrWrapper.eq(ActivityWhitelistEntity::getActivityId, activityId);
            activityWhitelist = activityWhitelistMapper.selectList(activityWhitelistrWrapper);
            if (activityWhitelist != null && activityWhitelist.size() > 0) {
                RedisUtil.set(activityWhitelistKey, activityWhitelist, redisOutTime, TimeUnit.MILLISECONDS);
                log.info("活动限制白名单列表，从数据库加载到redis缓存中，，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}",
                        activityWhitelistKey, JSONUtil.toJsonStr(activityWhitelist), redisOutTime, "TimeUnit.MILLISECONDS");
            }
        } else {
            log.info("用户参与限制条件，redis缓存，redisKey:{},redisValue:{},redisOutTime:{},TimeUnit:{}", activityWhitelistKey, JSONUtil.toJsonStr(activityWhitelist), redisOutTime, "TimeUnit.MILLISECONDS");
        }
        Map<String, ActivityWhitelistEntity> activityWhitesMap = activityWhitelist.stream().collect(Collectors.toMap(ActivityWhitelistEntity::getPhone, activityWhitelistEntity -> activityWhitelistEntity));
        return activityWhitesMap;
    }

}
